// @Desc:
// @CreateTime: 2020/10/12
package mlog

import (
	"io"
	"time"

	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"mycrm.com/config"
)

var Log *zap.SugaredLogger

// 初始化
func InitLogger() {
	writeSyncer := getLogWriter()
	encoder := getEncoder()
	core := zapcore.NewCore(encoder, writeSyncer, zapcore.InfoLevel)

	logger := zap.New(core)
	Log = logger.Sugar()
}

// 编码器(如何写入日志)
func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

// 指定日志将写到哪里去
func getLogWriter() zapcore.WriteSyncer {
	logPath := config.Configs.LogConf.LogPath
	return zapcore.AddSync(getWriter(logPath))
}

// 日志文件切割
func getWriter(filename string) io.Writer {
	// 保存日志30天，每24小时分割一次日志
	hook, err := rotatelogs.New(
		filename+"access_%Y%m%d.log",
		rotatelogs.WithLinkName(filename),
		rotatelogs.WithMaxAge(time.Hour*24*30),
		rotatelogs.WithRotationTime(time.Hour*24),
	)
	if err != nil {
		panic(err)
	}
	return hook
}
